using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using UpdaterManagement.Data;
using UpdaterManagement.Models;

namespace UpdaterManagement.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class ApiController : ControllerBase
    {
        private readonly ApplicationDbContext _context;

        public ApiController(ApplicationDbContext context)
        {
            _context = context;
        }

        [HttpGet("products")]
        public async Task<IActionResult> GetProducts(string? type = null)
        {
            var query = _context.Products.Where(v => true);
            
                if (!string.IsNullOrEmpty(type))
            {
               
                query = query.Where(v => v.Type == type);
            }
            
            var products = await query
                .Select(v => v.Name)
                .Distinct()
                .ToListAsync();
            return Ok(products);
        }

        [HttpGet("versions/{productName}")]
        public async Task<IActionResult> GetVersions(string productName)
        {
            var versions = await _context.VersionReleases
                .Where(v => v.ProductName == productName && v.IsActive)
                .OrderByDescending(v => v.CreatedTime)
                .Select(v => new { v.Version, FilePath = v.VersionUrl ?? v.FilePath })
                .ToListAsync();
            return Ok(versions);
        }
        
        [HttpPost("deployed-applications")]
        public async Task<IActionResult> CreateDeployedApplication([FromBody] CreateDeployedApplicationRequest request)
        {
            try
            {
                // 验证企业编号
                var enterprise = await _context.Enterprises
                    .FirstOrDefaultAsync(e => e.Code == request.EnterpriseCode);
                if (enterprise == null)
                {
                    return BadRequest("企业编号不存在");
                }
                
                // 检查相同服务名称和IP是否已存在
                var serverIp = request.ServerIp ?? "127.0.0.1";
                var existingApp = await _context.DeployedApplications
                    .FirstOrDefaultAsync(d => d.ServiceName == request.ServiceName && 
                                            d.ServerIp == serverIp && 
                                            d.EnterpriseId == enterprise.Id);
                if (existingApp != null)
                {
                    return Ok("服务已存在，无需重复添加");
                }
                
                var systemType = request.SystemType.ToUpper() == "IIS" ? "IIS站点" : "Windows服务";
                
                var deployedApp = new DeployedApplication
                {
                    ServiceName = request.ServiceName,
                    ServiceVersion = request.Version,
                    DeployPath = request.DeployPath,
                    SystemType = systemType,
                    IsActive = request.IsEnabled,
                    EnterpriseId = enterprise.Id,
                    ProductId = 1, // 默认产品ID
                    ServerIp = serverIp,
                    CreatedTime = DateTime.Now
                };
                
                _context.DeployedApplications.Add(deployedApp);
                await _context.SaveChangesAsync();
                
                return Ok("添加成功");
            }
            catch (Exception ex)
            {
                return BadRequest($"添加失败: {ex.Message}");
            }
        }
    }
    
    public class CreateDeployedApplicationRequest
    {
        public string ServiceName { get; set; } = "";
        public string ProductName { get; set; } = "";
        public string Version { get; set; } = "";
        public string DeployPath { get; set; } = "";
        public string SystemType { get; set; } = "";
        public bool IsEnabled { get; set; } = true;
        public string EnterpriseCode { get; set; } = "";
        public string? ServerIp { get; set; }
    }
}